class code1 {
    public String removeDuplicateLetters(String s) {
        int[] count = new int[26];//个数
        boolean[] instack = new boolean[26];//是否在栈中
        for(char x:s.toCharArray()) {
            count[x-'a']++;
        }
        StringBuilder st = new StringBuilder();

        for(char x:s.toCharArray()) {
            count[x-'a']--;

            //已经在栈中直接跳过
            if(instack[x-'a']) continue;
            //不在栈中
            //是否要出栈
            //1)小字符出现 && 后面存在栈顶的字符
            while(st.length()>0
                    && x < st.charAt(st.length()-1)
                    && count[st.charAt(st.length()-1)-'a'] > 0) {
                //出栈
                instack[st.charAt(st.length()-1)-'a'] = false;
                st.deleteCharAt(st.length()-1);
            }

            //入栈
            instack[x-'a'] = true;
            st.append(x);

        }


        return st.toString();

    }
}